package pri.damai.xiaowu.seckilling.server.service;

import com.google.common.collect.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.form.IdForm;
import pri.damai.xiaowu.common.core.util.ExceptionUtil;
import pri.damai.xiaowu.common.core.util.LocalUserUtils;
import pri.damai.xiaowu.common.core.vo.ResultVO;
import pri.damai.xiaowu.goods.client.SkuService;
import pri.damai.xiaowu.goods.common.command.StockReduceCmd;
import pri.damai.xiaowu.goods.common.vo.GoodsInfoVO;
import pri.damai.xiaowu.order.client.OrderRpcClient;
import pri.damai.xiaowu.order.common.dto.CreateOrderDTO;
import pri.damai.xiaowu.seckilling.common.dto.SeckillingDTO;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 并发秒杀
 *
 * @description
 * @author YangXinFu
 * @date 15:37 2022/6/13
 **/
@Service
public class SeckillingService   {

    @Resource
    SkuService skuService;
    @DubboReference
    OrderRpcClient orderRpcClient;


    public void seckilling1(SeckillingDTO seckillingDTO) {

        // 1. 首先判断库存是否满足
        Long goodsId = seckillingDTO.getGoodsId();
        ResultVO<GoodsInfoVO> resultVO = skuService.getSkuById(new IdForm(goodsId));
        ExceptionUtil.ifTureThrow(!resultVO.isSuccess(), resultVO.getMsg());
        GoodsInfoVO goodsInfo = resultVO.getData();
        ExceptionUtil.isNull(goodsInfo, "无此商品。");
        ExceptionUtil.ifTureThrow(seckillingDTO.getSeckillingNum() > resultVO.getData().getStockNum(),
                "商品已售罄。");


        // 2. 开始扣减库存
        StockReduceCmd stockReduceCmd = new StockReduceCmd();
        stockReduceCmd.setReduceNum(seckillingDTO.getSeckillingNum());
        stockReduceCmd.setSkuId(seckillingDTO.getGoodsId());
        skuService.reduceSku(stockReduceCmd);

        // 3. 生成订单
        CreateOrderDTO createOrderDTO = new CreateOrderDTO();
        CreateOrderDTO.OrderGoods orderGoods = new CreateOrderDTO.OrderGoods();
        orderGoods.setSkuId(goodsInfo.getId());
        orderGoods.setGoodsNum(seckillingDTO.getSeckillingNum());
        orderGoods.setGoodsMainImg(goodsInfo.getMainUrl()==null?null:goodsInfo.getMainUrl().get(0));
        orderGoods.setSellingPrice(goodsInfo.getPriceFee());
        orderGoods.setOriginalPrice(goodsInfo.getMarketPriceFee());
        orderGoods.setSettlementPrice(goodsInfo.getPriceFee());
        ArrayList<CreateOrderDTO.OrderGoods> list = Lists.newArrayList(orderGoods);
        createOrderDTO.setGoodsList(list);
        createOrderDTO.setUserId(LocalUserUtils.getLocalUserId());
        orderRpcClient.createOrder(createOrderDTO);
    }

}
